package org.ragdollcat.secondaiagent.advisor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.advisor.api.*;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.model.Generation;
import reactor.core.publisher.Flux;

import java.lang.reflect.Array;
import java.util.Collections;
import java.util.List;

/**
 * 自定义敏感词校验
 */
@Slf4j
public class SensitiveWordCheckAdvisor implements CallAroundAdvisor, StreamAroundAdvisor {

    /**
     * 定义敏感词，实际上应该调用第三方API或者从数据库中读取
     */
    private static final List<String> sensitiveWords = List.of("黄威橙");


    /**
     * 前置校验
     * @param advisedRequest
     * @return
     */
    public boolean beforeCheck(AdvisedRequest advisedRequest){
        log.info("开始校验敏感词");
        String userTest = advisedRequest.userText();
        for (String sensitiveWord : sensitiveWords) {
            if (userTest.contains(sensitiveWord)){
                return false;
            }
        }
        return true;
    }

    /**
     * Around advice that wraps the ChatModel#call(Prompt) method.
     *
     * @param advisedRequest the advised request
     * @param chain          the advisor chain
     * @return the response
     */
    @Override
    public AdvisedResponse aroundCall(AdvisedRequest advisedRequest, CallAroundAdvisorChain chain) {
        if (!beforeCheck(advisedRequest)){
            throw new RuntimeException("抱歉，您的问题我无法回答！");
        }
        return chain.nextAroundCall(advisedRequest);
    }

    /**
     * Around advice that wraps the invocation of the advised request.
     *
     * @param advisedRequest the advised request
     * @param chain          the chain of advisors to execute
     * @return the result of the advised request
     */
    @Override
    public Flux<AdvisedResponse> aroundStream(AdvisedRequest advisedRequest, StreamAroundAdvisorChain chain) {
        if (!beforeCheck(advisedRequest)){
            throw new RuntimeException("抱歉，您的问题我无法回答！");
        }
        return chain.nextAroundStream(advisedRequest);
    }

    /**
     * Return the name of the advisor.
     *
     * @return the advisor name.
     */
    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
